class IndexManager {
    constructor() {
        this.initializeEventListeners();
        this.startAutoRefresh();
    }

    initializeEventListeners() {
        // 紧急停止按钮
        const emergencyBtn = document.querySelector('.action-btn.emergency');
        if (emergencyBtn) {
            emergencyBtn.addEventListener('click', this.handleEmergencyStop.bind(this));
        }

        // 生成报表按钮
        const reportBtn = document.querySelector('.action-btn.report');
        if (reportBtn) {
            reportBtn.addEventListener('click', this.handleGenerateReport.bind(this));
        }

        // 移动端菜单切换
        const menuToggle = document.querySelector('.menu-toggle');
        if (menuToggle) {
            menuToggle.addEventListener('click', this.toggleMenu.bind(this));
        }
    }

    async handleEmergencyStop() {
        if (confirm('确定要执行紧急停止操作吗？')) {
            try {
                const response = await fetch('/api/emergency-stop', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    alert('紧急停止指令已发送');
                } else {
                    throw new Error('操作失败');
                }
            } catch (error) {
                console.error('紧急停止操作失败:', error);
                alert('紧急停止操作失败，请立即联系管理员！');
            }
        }
    }

    async handleGenerateReport() {
        try {
            const response = await fetch('/api/generate-report', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = '生产报表.pdf';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            } else {
                throw new Error('报表生成失败');
            }
        } catch (error) {
            console.error('报表生成失败:', error);
            alert('报表生成失败，请稍后重试');
        }
    }

    toggleMenu() {
        const sideMenu = document.querySelector('.side-menu');
        if (sideMenu) {
            sideMenu.classList.toggle('active');
        }
    }

    startAutoRefresh() {
        // 每30秒刷新一次数据
        setInterval(this.refreshData.bind(this), 30000);
    }

    async refreshData() {
        try {
            const response = await fetch('/api/dashboard-data');
            if (response.ok) {
                const data = await response.json();
                this.updateKPIs(data.kpis);
                this.updateAlerts(data.alerts);
            }
        } catch (error) {
            console.error('数据刷新失败:', error);
        }
    }

    updateKPIs(kpis) {
        // 更新KPI数据显示
        const progressBar = document.querySelector('.progress');
        if (progressBar && kpis.progress) {
            progressBar.style.width = `${kpis.progress}%`;
            progressBar.nextElementSibling.textContent = `${kpis.progress}%`;
        }
    }

    updateAlerts(alerts) {
        // 更新预警信息
        const alertList = document.querySelector('.alert-list');
        if (alertList) {
            alertList.innerHTML = alerts.map(alert => `
                <div class="alert-item ${alert.level}">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>${alert.message}</span>
                    <span class="alert-time">${alert.time}</span>
                </div>
            `).join('');
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new IndexManager();
}); 